package com.telnikoff.gf;

import java.awt.Container;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.MenuElement;

public class DefaultHost implements GfHost
{
	private final JFrame frame;
	
	protected DefaultHost()
	{
		frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(600, 400);
		frame.setLocationRelativeTo(null);
	}

	public <T extends JComponent> Container getContainer(GfGuest<T> guest) 
	{
		frame.setTitle(guest.getName());
		Container c = frame.getContentPane();
		c.removeAll();
		return c;
	}
	
	public void setMenu(GfMenu m)
	{
		JMenuBar bar = frame.getJMenuBar();
		
		if (null != bar)
			frame.remove(bar);
		
		bar = new JMenuBar();

		apply(bar, m);
		
		if (!m.isEmpty())
			frame.setJMenuBar(bar);
	}
	
	private void apply(MenuElement m, GfMenuNode n)
	{
		if (m instanceof JMenuBar)
		{
			if (n instanceof GfMenu)
			{
				GfMenu gfMenu = (GfMenu)n;
				for (GfMenuBranch br : gfMenu.getBranches())
				{
					apply(m, br);
				}
			}
			else if (n instanceof GfMenuBranch)
			{
				GfMenuBranch branch = (GfMenuBranch)n;
				JMenuBar bar = (JMenuBar)m;
				JMenu    jm  = new JMenu(branch.getName());
				bar.add(jm);
				for (GfMenuNode node : branch.getNodes())
					apply(jm, node);
			}
		}
		else if (m instanceof JMenu)
		{
			if (n instanceof GfMenuBranch)
			{
				GfMenuBranch branch = (GfMenuBranch)n;
				JMenu parent = (JMenu)m;
				JMenu child  = new JMenu(branch.getName());
				parent.add(child);
				for (GfMenuNode node : branch.getNodes())
					apply(child, node);
			}
			else if (n instanceof GfMenuLeaf)
			{
				GfMenuLeaf leaf = (GfMenuLeaf)n;
				((JMenu)m).add(new JMenuItem(leaf.getAction()));
			}
		}
	}
	
	public void show()
	{
		frame.setVisible(true);
	}
	
}